package handles

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"pet-master/cache"
	"pet-master/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	pet_name := c.PostForm("pet_name")
	pet_type := c.PostForm("pet_type")

	data := models.Pet{

		PetName: pet_name,
		PetType: pet_type,
	}

	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var pet []models.Pet
	redis_key := "list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&pet)
		jsinData, _ := json.Marshal(pet)
		cache.Rdb.Set(cache.Ctx, redis_key, jsinData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &pet)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "成功",
		"data": pet,
	})
	return
}

func Del(c *gin.Context) {
	id := c.PostForm("id")

	var pet models.Pet
	err := models.DB.Where("id=?", id).Delete(&pet).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
